import { defineStore } from 'pinia'
import { useQuery, useMutation } from '@tanstack/vue-query'
import api from '../api'

export const useUserPermissionStore = defineStore('userPermission', {
  state: () => ({
    users: [],
    familyTreeUsers: [],
    currentUser: null,
    isSystemAdmin: false,
    selectedFamilyTree: null
  }),
  
  getters: {
    getUsers: (state) => state.users,
    getFamilyTreeUsers: (state) => state.familyTreeUsers,
    getCurrentUser: (state) => state.currentUser,
    getIsSystemAdmin: (state) => state.isSystemAdmin,
    getSelectedFamilyTree: (state) => state.selectedFamilyTree
  },
  
  actions: {
    setUsers(users) {
      this.users = users
    },
    
    setFamilyTreeUsers(users) {
      this.familyTreeUsers = users
    },
    
    setCurrentUser(user) {
      this.currentUser = user
      this.isSystemAdmin = user?.role === 'ADMIN'
    },
    
    setSelectedFamilyTree(treeId) {
      this.selectedFamilyTree = treeId
    },
    
    // 获取当前用户信息的 useQuery 配置
    useFetchCurrentUser() {
      return useQuery({
        queryKey: ['current-user'],
        queryFn: () => api.get('/auth/info'),
        onSuccess: (result) => {
          if (result.data.code === 200) {
            this.setCurrentUser(result.data.data)
          }
        },
        onError: (error) => {
          console.error('获取当前用户信息失败:', error)
        }
      })
    },
    
    // 获取用户列表的 useQuery 配置
    useFetchUsers() {
      return useQuery({
        queryKey: ['users'],
        queryFn: () => api.get('/users'),
        onSuccess: (result) => {
          if (result.data.code === 200) {
            this.users = result.data.data || []
          } else {
            console.error('获取用户列表失败:', result.data.msg)
          }
        },
        onError: (error) => {
          console.error('获取用户列表失败:', error)
        }
      })
    },
    
    // 创建用户的 useMutation 配置
    useCreateUser() {
      return useMutation({
        mutationFn: (userData) => api.post('/users', userData),
        onError: (error) => {
          console.error('创建用户失败:', error)
        }
      })
    },
    
    // 更新用户的 useMutation 配置
    useUpdateUser() {
      return useMutation({
        mutationFn: ({ id, data }) => api.put(`/users/${id}`, data),
        onError: (error) => {
          console.error('更新用户失败:', error)
        }
      })
    },
    
    // 删除用户的 useMutation 配置
    useDeleteUser() {
      return useMutation({
        mutationFn: (id) => api.delete(`/users/${id}`),
        onError: (error) => {
          console.error('删除用户失败:', error)
        }
      })
    },
    
    // 获取家族树用户列表的 useQuery 配置
    useFetchFamilyTreeUsers() {
      return useQuery({
        queryKey: ['family-tree-users', this.selectedFamilyTree],
        queryFn: () => api.get(`/user-family/family-tree/${this.selectedFamilyTree}`),
        enabled: !!this.selectedFamilyTree,
        onSuccess: (result) => {
          this.familyTreeUsers = result.data.data || []
        },
        onError: (error) => {
          console.error('获取家族树用户失败:', error)
        }
      })
    },
    
    // 更新用户家族角色的 useMutation 配置
    useUpdateUserFamilyRole() {
      return useMutation({
        mutationFn: ({ id, role }) => api.put(`/user-family/${id}/role`, { role }),
        onError: (error) => {
          console.error('更新用户家族角色失败:', error)
        }
      })
    },
    
    // 添加用户到家族树的 useMutation 配置
    useAddUserToFamily() {
      return useMutation({
        mutationFn: (userFamilyData) => api.post('/user-family', userFamilyData),
        onError: (error) => {
          console.error('添加用户到家族树失败:', error)
        }
      })
    },
    
    // 从家族树移除用户的 useMutation 配置
    useRemoveUserFromFamily() {
      return useMutation({
        mutationFn: (id) => api.delete(`/user-family/${id}`),
        onError: (error) => {
          console.error('从家族树移除用户失败:', error)
        }
      })
    }
  }
})